#include <QLabel>
#include <QFileInfo>
#include <QHeaderView>

#include "homeview.h"

///////// Class 'HomeViewTopBannerButton' declaration //////////////////////////////////////////////

HomeViewTopBannerButton::HomeViewTopBannerButton(const QPixmap & pixmap, QWidget * parent)
    : QLabel(parent)
{
    setPixmap(pixmap);
}

///////// Class 'HomeViewTopBannerWidget' declaration //////////////////////////////////////////////

HomeViewTopBannerWidget::HomeViewTopBannerWidget(const QString & text, QWidget * parent)
    : QWidget(parent)
{
    QHBoxLayout * mainLayout = new QHBoxLayout(this);
    mainLayout->setContentsMargins(0, 0, 0, 0);

//    QVBoxLayout * labelLayout = new QVBoxLayout(this);
//    labelLayout->setContentsMargins(0, 0, 0, 0);
    m_label = new QLabel(text, this);
    m_label->setMargin(0);
    m_label->setAlignment(Qt::AlignTop);
    mainLayout->addWidget(m_label);
    mainLayout->addSpacing(4);
//    labelLayout->addStretch(1);
//    mainLayout->addLayout(labelLayout);

    HomeViewTopBannerButton * button = new HomeViewTopBannerButton(QPixmap(":/banners/feedback"), this);
    mainLayout->addWidget(button, 0, Qt::AlignTop);

    setLayout(mainLayout);
}

///////// Class 'HomeViewWidget' declaration ///////////////////////////////////////////////////////

HomeViewTopBanner::HomeViewTopBanner(QWidget * parent)
    : QWidget(parent)
{
    setFixedHeight(60);

    QHBoxLayout * mainLayout = new QHBoxLayout(this);
    mainLayout->setContentsMargins(0, 0, 0, 0);

    HomeViewTopBannerWidget * bannerWidget = new HomeViewTopBannerWidget("<font color = #88aa00><b>Let's make it better!</b>\n"\
                                                                         "<br>Report bugs\n"\
                                                                         "<br>Suggest new features.<\font>", this);
    mainLayout->addWidget(bannerWidget, 0, Qt::AlignTop);

    mainLayout->addStretch();

    QLabel * logoLabel = new QLabel(this);
    logoLabel->setPixmap(QPixmap(":/view/logo"));
    mainLayout->addWidget(logoLabel);

    setLayout(mainLayout);
}

///////// Class 'HomeViewWidget' declaration ///////////////////////////////////////////////////////

HomeViewAction::HomeViewAction(QAction * action, QWidget * parent)
    : QWidget(parent)
{
    m_action = action;

    QHBoxLayout * layout = new QHBoxLayout(this);
    layout->setContentsMargins(0, 0, 0, 0);

    QLabel * pixmapLabel = new QLabel(this);
    pixmapLabel->setPixmap(action->icon().pixmap(20, 20));

    layout->addWidget(pixmapLabel);

    QLabel * textLabel = new QLabel(action->text(), this);

    layout->addWidget(textLabel, 1);
    setCursor(Qt::PointingHandCursor);
}

void HomeViewAction::mousePressEvent(QMouseEvent *)
{
    m_action->activate(QAction::Trigger);
}

///////// Class 'HomeViewWidget' declaration ///////////////////////////////////////////////////////

HomeViewActionsList::HomeViewActionsList(QWidget * parent)
    : QWidget(parent)
{
    QVBoxLayout * mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(0, 0, 0, 0);

    m_layout = new QVBoxLayout(this);
    m_layout->setContentsMargins(0, 0, 0, 0);
    m_layout->setSpacing(8);
    mainLayout->addLayout(m_layout);
    mainLayout->addStretch();

    setLayout(mainLayout);

    QFile styleFile(":/qss/actionslist");
    styleFile.open(QFile::ReadOnly);
    setStyleSheet(styleFile.readAll());
}

void HomeViewActionsList::addActionItem(QAction * action)
{
    HomeViewAction * actionWidget = new HomeViewAction(action, this);
    m_layout->addWidget(actionWidget);
}

///////// Class 'HomeViewRecentModel' declaration //////////////////////////////////////////////////

HomeViewRecentModel::HomeViewRecentModel(QObject *parent)
    : QAbstractTableModel(parent)
{

}

int HomeViewRecentModel::rowCount(const QModelIndex &parent) const
{
    return m_list.count();
}

int HomeViewRecentModel::columnCount(const QModelIndex &parent) const
{
    return 2;
}

QVariant HomeViewRecentModel::data(const QModelIndex &index, int role) const
{
    RecentFile file = m_list.at(index.row());

    if(role == Qt::DisplayRole || role == Qt::AccessibleTextRole)
    {
        if(index.column() == 0)
            return file.first;

        if(index.column() == 1)
            return file.second;
    }

//    if(role == Qt::ToolTipRole)
//        return file.first;

    if(role == Qt::UserRole && index.column() == 0)
        return file.first;

    return QVariant();
}

QVariant HomeViewRecentModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if(role == Qt::DisplayRole)
    {
        if(section == 0)
            return tr("File Name");

        if(section == 1)
            return tr("Last Opened");
    }

    return QVariant();
}

void HomeViewRecentModel::addRecentFile(const RecentFile & file)
{
    for(int i = 0; i < m_list.count(); i++)
    {
        RecentFile recentFile = m_list.at(i);
        if(recentFile.first == file.first)
        {
            recentFile.second = file.second;
            m_list.replace(i, recentFile);
            emit layoutChanged();
            return;
        }
    }

    m_list.append(file);
    emit layoutChanged();
}

int HomeViewRecentModel::recentFilesCount() const
{
    return m_list.count();
}

RecentFile HomeViewRecentModel::recentFile(int index) const
{
    return m_list.at(index);
}

///////// Class 'HomeViewWidget' declaration ///////////////////////////////////////////////////////

HomeViewRecentTable::HomeViewRecentTable(QWidget * parent)
    : QTableView(parent)
{
//    QStringList headerLabels;
//    headerLabels << tr("File Name") << tr("Last Opened");

//    setColumnCount(2);
//    setHorizontalHeaderLabels(headerLabels);
    QHeaderView * header = horizontalHeader();
    header->setStretchLastSection(true);

    header = verticalHeader();
    header->hide();

//    setColumnWidth(1, 200);
    setShowGrid(false);
    setSelectionMode(QAbstractItemView::SingleSelection);
    setSelectionBehavior(QAbstractItemView::SelectRows);

    QFile styleFile(":/qss/recenttable");
    styleFile.open(QFile::ReadOnly);
    setStyleSheet(styleFile.readAll());
    setMinimumWidth(600);
    setMouseTracking(true);

    connect(this, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(itemClicked(QModelIndex)));
//    connect(this, SIGNAL(entered(QModelIndex)), this, SLOT(itemEntered(QModelIndex)));
}

void HomeViewRecentTable::setModel(QAbstractItemModel *model)
{
    QTableView::setModel(model);

    QHeaderView * header = horizontalHeader();
    header->resizeSection(0, 400);
}

void HomeViewRecentTable::itemClicked(const QModelIndex & index)
{
    if(index.column() != 0)
        return;

    emit openFile(index.data(Qt::UserRole).toString());
}

//void HomeViewRecentTable::addRecentItem(const QString & fileName, const QDateTime lastOpened)
//{
//    QFileInfo fileInfo(fileName);
//    int row = rowCount();
//    setRowCount(row + 1);

//    QTableWidgetItem * fileItem = new QTableWidgetItem(fileInfo.fileName());
//    fileItem->setData(Qt::UserRole, fileName);
//    setItem(row, 0, fileItem);

//    QTableWidgetItem * dateItem = new QTableWidgetItem(lastOpened.toString());
//    setItem(row, 1, dateItem);
//}

///////// Class 'HomeViewSettings' declaration /////////////////////////////////////////////////////

HomeViewSettings::HomeViewSettings(QObject * parent)
    : QObject(parent)
{
    m_recentFilesModel = new HomeViewRecentModel(this);
}

HomeViewRecentModel * HomeViewSettings::recentFilesModel() const
{
    return m_recentFilesModel;
}

///////// Class 'HomeViewWidget' declaration ///////////////////////////////////////////////////////

HomeViewWidget::HomeViewWidget(HomeViewSettings * settings, QWidget * parent)
    : ViewWidget(parent)
{
    m_settings = settings;

    QHBoxLayout * viewLayout = new QHBoxLayout(this);
    viewLayout->setContentsMargins(0, 0, 0, 30);
    viewLayout->addStretch();

    QVBoxLayout * mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(0, 0, 0, 0);

    HomeViewTopBanner * topBanner = new HomeViewTopBanner(this);
    mainLayout->addWidget(topBanner);

    mainLayout->addSpacing(80);

    QFrame * frame = new QFrame(this);
    frame->setFrameStyle(QFrame::HLine);
    mainLayout->addWidget(frame);

//    QLabel * titleLabel = new QLabel(("<font size = 32 face = \"Arial\">Home Page</font>"), this);
//    titleLabel->setAlignment(Qt::AlignCenter);
//    mainLayout->addWidget(titleLabel);

//    frame = new QFrame(this);
//    frame->setFrameStyle(QFrame::HLine);
//    mainLayout->addWidget(frame);

    QHBoxLayout * hLayout = new QHBoxLayout(this);

    HomeViewActionsList * actionsList = new HomeViewActionsList(this);
    QAction * action = new QAction(tr("Open Log File"), this);
    connect(action, SIGNAL(triggered()), this, SLOT(openFileClicked()));
    actionsList->addActionItem(action);
    action = new QAction(tr("View Documentation"), this);
    connect(action, SIGNAL(triggered()), this, SIGNAL(openDocumentation()));
    actionsList->addActionItem(action);
    hLayout->addWidget(actionsList);
    hLayout->addSpacing(80);

    m_recentTable = new HomeViewRecentTable(this);
    connect(m_recentTable, SIGNAL(openFile(QString)), this, SIGNAL(openFile(QString)));
    m_recentTable->setModel(m_settings->recentFilesModel());

    hLayout->addWidget(m_recentTable);
    mainLayout->addLayout(hLayout, 1);

    viewLayout->addLayout(mainLayout);

    viewLayout->addStretch();
}

QString HomeViewWidget::pluginName() const
{
    return "homepage";
}

void HomeViewWidget::adjustToolbar(const ToolBarItemList &itemsList) const
{
}

void HomeViewWidget::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.fillRect(rect(), Qt::white);
}

void HomeViewWidget::openFileClicked()
{
    emit openFile(QString());
}

//void HomeViewWidget::updateRecentFilesList()
//{
//    m_recentTable->clear();
//    for(int i = 0; i < m_settings->recentFilesCount(); i++)
//    {
//        RecentFile file = m_settings->recentFile(i);
//        m_recentTable->addRecentItem(file.first, file.second);
//    }
//}

///////// Class 'HomeViewPlugin' declaration ///////////////////////////////////////////////////////

HomeViewPlugin::HomeViewPlugin(QObject * parent)
    : QObject(parent)
{
    m_settings = new HomeViewSettings(this);
}

QString HomeViewPlugin::name()const
{
    return "homepage";
}

QString HomeViewPlugin::description()const
{
    return tr("This plugin provides home page with shortcuts to application features");
}

void HomeViewPlugin::saveSettings()
{
    QFile settingsFile("plugins\\homeviewsettings.xml");
    if(!settingsFile.open(QFile::WriteOnly))
        return;

    QDomDocument doc;
    QDomElement rootElement = doc.createElement("recentFiles");
    doc.appendChild(rootElement);
    for(int i = 0; i < m_settings->recentFilesModel()->recentFilesCount(); i++)
    {
        RecentFile recentFile = m_settings->recentFilesModel()->recentFile(i);
        QDomElement fileElement = doc.createElement("file");
        fileElement.setAttribute("path", recentFile.first);
        fileElement.setAttribute("lastOpened", recentFile.second.toString(Qt::ISODate));
        rootElement.appendChild(fileElement);
    }

    settingsFile.write(doc.toString(4).toAscii());
    settingsFile.close();
}

bool HomeViewPlugin::loadSettings()
{
    QFile settingsFile("plugins\\homeviewsettings.xml");
    if(!settingsFile.open(QFile::ReadOnly))
        return true;

    QDomDocument doc;
    if(!doc.setContent(settingsFile.readAll()))
        return true;

    settingsFile.close();

    QDomElement rootElement = doc.firstChildElement();
    QDomElement fileElement = rootElement.firstChildElement();

    while(!fileElement.isNull())
    {
        m_settings->recentFilesModel()->addRecentFile(RecentFile(fileElement.attribute("path"),
                                                      QDateTime::fromString(fileElement.attribute("lastOpened"), Qt::ISODate)));
        fileElement = fileElement.nextSiblingElement();
    }

    return true;
}

QString HomeViewPlugin::viewName()const
{
    return tr("Home");
}

ViewWidget::ViewType HomeViewPlugin::viewType() const
{
    return ViewWidget::DummyView;
}

QIcon HomeViewPlugin::icon(bool active)const
{
//    QPixmap pixmap(20, 20);
//    pixmap.fill(Qt::green);
    return QIcon(":/icons/view_active");
}

ViewWidget * HomeViewPlugin::createView(QWidget * parent)const
{
    HomeViewWidget * viewWidget = new HomeViewWidget(m_settings, parent);

    return viewWidget;
}

ToolBarItemList HomeViewPlugin::toolBarItems(QObject * parent)const
{
    return ToolBarItemList();
}

SettingsWidget * HomeViewPlugin::settingsWidget(QWidget * parent)const
{
    return 0;
}

void HomeViewPlugin::appEvent(AppEvent *event)
{
    if(event->type() != AppEvent::EventOpenFile)
        return;

    AppEventOpenFile * openFileEvent = static_cast<AppEventOpenFile *>(event);
    m_settings->recentFilesModel()->addRecentFile(RecentFile(openFileEvent->path(), openFileEvent->date()));
    saveSettings();
}

////////////////////////////////////////////////////////////////////////////////////////////////////

Q_EXPORT_PLUGIN2(homeview, HomeViewPlugin)

////////////////////////////////////////////////////////////////////////////////////////////////////
